package com.xg.serviceOrder.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xg.common.constant.CarConstant;
import com.xg.common.constant.RedisKeyConstant;
import com.xg.common.request.OrderItemDTO;
import com.xg.serviceOrder.entity.UsedCarOrder;
import com.xg.serviceOrder.entity.UserAddress;
import com.xg.serviceOrder.mapper.UsedCarOrderMapper;
import com.xg.serviceOrder.mapper.UserAddressMapper;
import com.xg.serviceOrder.remote.ServiceCarFeignClient;
import com.xg.serviceOrder.service.UsedCarOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.UUID;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author li
 * @since 2023-04-03
 */
@Service
public class UsedCarOrderServiceImpl extends ServiceImpl<UsedCarOrderMapper, UsedCarOrder> implements UsedCarOrderService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UsedCarOrderMapper usedCarOrderMapper;

    @Autowired
    private ServiceCarFeignClient serviceCarFeignClient;

    @Autowired
    private UserAddressMapper userAddressMapper;

    /**
     * 初创订单
     * @param carId
     * @return
     */
    @Transactional
    @Override
    public UsedCarOrder add(Long carId) {

        // 是否已创建订单,购物车存在商品,返回


        UsedCarOrder usedCarOrder = new UsedCarOrder();

        // 根据token中用户信息，查询出默认地址信息
        QueryWrapper<UserAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",1)
                        .eq("is_default", CarConstant.IMG_IS_DEFAULT);
        UserAddress userAddress = userAddressMapper.selectOne(queryWrapper);

        // 根据车辆id查询车辆信息；
        OrderItemDTO orderCarInfo = serviceCarFeignClient.getCarByCarId(carId);
        BeanUtils.copyProperties(orderCarInfo,usedCarOrder);
        if (null != userAddress){
            usedCarOrder.setUserAddress(userAddress.getAddressText());
            usedCarOrder.setAddressPhone(userAddress.getAddressPhone());
            usedCarOrder.setAddressUser(userAddress.getAddressUser());
        }
        // 生成订单号
        String orderNumber = UUID.randomUUID().toString().replace("-", "");
        usedCarOrder.setOrderNumber(orderNumber);
        // 新增订单
        usedCarOrderMapper.insert(usedCarOrder);
        String orderKey = RedisKeyConstant.ORDER_TOKEN_PREFIX+usedCarOrder.getOrderId();
        redisTemplate.opsForValue().set(orderKey,orderNumber);
        return usedCarOrder;
    }




}
